package com.smart.manager.weixin.mp;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.StrUtil;
import com.alicp.jetcache.Cache;
import com.smart.common.cache.CacheService;
import com.smart.manager.member.entities.models.MemberProfileMain;
import com.smart.manager.member.entities.models.query.QMemberProfileMain;
import com.smart.manager.pop.entities.models.PopDisBill;
import com.smart.manager.pop.entities.models.PopDisInviter;
import com.smart.manager.system.repository.ConfigRepository;
import com.smart.manager.union.egg.models.UnionEggOrder;
import com.smart.manager.weixin.mp.repository.WxmpAccountRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpTemplateMsgService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;


/**
 * 微信公众号模板消息
 *
 * @author Administrator
 */
@Service
@RequiredArgsConstructor
@Log4j2
public class MbMsgService {

    private final WxmpAccountRepository wxmpAccountRepository;

    private final WxMpService wxMpService;
    private final CacheService cacheService;
    private final ConfigRepository configRepository;

    /**
     * 获取微信模板消息服务
     */
    private WxMpTemplateMsgService getTemplateMsgService() {
        String defaultAppId = wxmpAccountRepository.getDefaultAppId();
        return wxMpService.switchoverTo(defaultAppId).getTemplateMsgService();
    }


    private String getMpOpenId(Long memberId) {
        Cache<Long, String> mpOpenIdCache = cacheService.getMpOpenIdCache();
        String s = mpOpenIdCache.get(memberId);
        if (StrUtil.isNotBlank(s)) {
            return s;
        }
        String openId = new QMemberProfileMain().id.eq(memberId).select(
                QMemberProfileMain.Alias.wxMpId
        ).setMaxRows(1).findSingleAttribute();

        if (StrUtil.isBlank(openId)) {
            mpOpenIdCache.put(memberId, openId);
        }
        return openId;


    }



    /**
     * 订单创建成功同志
     * */

    @Async
    public void whenOrderCreate(Long memberId, Long orderId, String productName, LocalDateTime sendTime, String nickName ,String url) {
        String mpOpenId = getMpOpenId(memberId);
        if (StrUtil.isBlank(mpOpenId)) {
            return;
        }

        try {
            String t3 = sendTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
            ArrayList<WxMpTemplateData> msgData = new ArrayList<>();
            msgData.add(new WxMpTemplateData("character_string2", orderId.toString()));
            msgData.add(new WxMpTemplateData("thing12", productName));
            msgData.add(new WxMpTemplateData("time3", t3));
            msgData.add(new WxMpTemplateData("thing6", nickName));
            WxMpTemplateMessage message = new WxMpTemplateMessage();
            message.setToUser(mpOpenId);
            message.setData(msgData);
            message.setTemplateId("rp3LlslKaKT-PpAcJ0Z1aZKymq2tT5VxEcagMjomNIw");
            message.setUrl(url);
            getTemplateMsgService().sendTemplateMsg(message);
        } catch (Exception e) {
            log.warn("订单提交成功通知的模板消息发送失败:" + e.getMessage());
        }


    }


    /**
     * 顶订单发货通知
     * */
    public void whenEggOrderReplenishExpress(UnionEggOrder record) {
        String mpOpenId = getMpOpenId(record.getMember().getId());
        if (StrUtil.isBlank(mpOpenId)) {
            return;
        }
        try {

            String t3 = record.getSendTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
            ArrayList<WxMpTemplateData> msgData = new ArrayList<>();
            msgData.add(new WxMpTemplateData("character_string12", record.getId().toString()));
            msgData.add(new WxMpTemplateData("thing14", record.getTitle()));
            msgData.add(new WxMpTemplateData("thing21", record.getExpressName()));
            msgData.add(new WxMpTemplateData("character_string1", record.getExpressCode()));
            msgData.add(new WxMpTemplateData("time3", t3));
            WxMpTemplateMessage message = new WxMpTemplateMessage();
            message.setToUser(mpOpenId);
            message.setData(msgData);
            message.setTemplateId("xOUVxoHF9wog-H6BJTHJ2Bdva0ZezLy765L5ZltWKwY");
            getTemplateMsgService().sendTemplateMsg(message);
        } catch (Exception e) {
            log.warn("订单发货通知的模板消息发送失败:" + e.getMessage());
        }
    }


    public void whenB2cBindSuccess(MemberProfileMain newMember, PopDisInviter popDisInviter) {

        String templateId = "Cm7fmOLURC_iQftfqhdOg5aa813BQgimrK3t_jnBvnU";
        String openid =  popDisInviter.getOpenid() ;
        String string = configRepository.readCache("H5URL").getString("url");
        String url = string+"/#/pages/index/group";
        if (StrUtil.isBlank(openid)) {
            return;
        }
        try {
            String phone = DesensitizedUtil.mobilePhone(newMember.getPhoneNumber());
            String t3 = LocalDateTimeUtil.formatNormal(LocalDateTime.now()) ;
            ArrayList<WxMpTemplateData> wxMpTemplateDataArrayList = new ArrayList<>();
            wxMpTemplateDataArrayList.add(new WxMpTemplateData("thing1",  newMember.getNickName()));
            wxMpTemplateDataArrayList.add(new WxMpTemplateData("phone_number3", phone));
            wxMpTemplateDataArrayList.add(new WxMpTemplateData("time2", t3));
            WxMpTemplateMessage message = new WxMpTemplateMessage();
            message.setData(wxMpTemplateDataArrayList);
            message.setTemplateId(templateId);
            message.setToUser(openid);
            message.setUrl(url);
            getTemplateMsgService().sendTemplateMsg(message);
        } catch (Exception e) {
            log.warn("订单提交成功通知的模板消息发送失败:" + e.getMessage());
        }


    }


    /**
     * 佣金推广
     * @param popDisInviter
     */
    public void streamBindSuccess(PopDisInviter popDisInviter, PopDisBill popDisBill) {

        String templateId = "5NvLMwKcJ_TcUtZ1RdnJkUqkYJEg_XHMpj39rKFMV0A";
        String openid =  popDisInviter.getOpenid() ;
        String string = configRepository.readCache("H5URL").getString("url");
        String url = string+ "/#/pages/index/money";
        if (StrUtil.isBlank(openid)) {
            return;
        }
        try {
            String time2 = LocalDateTimeUtil.formatNormal(popDisBill.getCreateTime()) ;
            String code = popDisBill.getCode();
            String label = popDisBill.getKind().getLabel();
            String amount14 = popDisBill.getAmount().toString();
            ArrayList<WxMpTemplateData> wxMpTemplateDataArrayList = new ArrayList<>();
            wxMpTemplateDataArrayList.add(new WxMpTemplateData("character_string11",  code));
            wxMpTemplateDataArrayList.add(new WxMpTemplateData("amount14", amount14));
            wxMpTemplateDataArrayList.add(new WxMpTemplateData("thing6", label));
            wxMpTemplateDataArrayList.add(new WxMpTemplateData("time2", time2));
            wxMpTemplateDataArrayList.add(new WxMpTemplateData("amount16", popDisInviter.getAmount().toString()));
            WxMpTemplateMessage message = new WxMpTemplateMessage();
            message.setData(wxMpTemplateDataArrayList);
            message.setTemplateId(templateId);
            message.setToUser(openid);
            message.setUrl(url);
            getTemplateMsgService().sendTemplateMsg(message);
        } catch (Exception e) {
            log.warn("代理提交成功通知的模板消息发送失败:" + e.getMessage());
        }
    }
}
